package org.yusys.dtm.sharejdbc;
import java.util.*;

public class WeightCalculator {

    //定义了一个 List<WeightEntry> 类型的 weightEntries 列表，用于存储每个键及其对应的权重
    private List<WeightEntry> weightEntries = new ArrayList<>();
    //totalWeight 变量，用于存储所有键的权重总和
    private int totalWeight = 0;
    //用于保存key的权重区间
    private HashMap<String,String> weightsRegion = new HashMap<String,String>();
    public WeightCalculator(String[] keys, int[] weights) {
        if (keys.length != weights.length || keys.length > 100) {
            throw new IllegalArgumentException("输入的键值对数量不匹配或键的数量超过限制");
        }
        for (int i = 0; i < keys.length; i++) {
            if (weights[i] < 0 || weights[i] > 500) {
                throw new IllegalArgumentException("权重值超出范围");
            }
            weightEntries.add(new WeightEntry(keys[i], weights[i]));
            totalWeight += weights[i];
        }
        int cumulativeWeight = 0;
        for (WeightEntry entry : weightEntries) {
            int start = cumulativeWeight;
            cumulativeWeight += entry.weight;
            String region = start + "," + cumulativeWeight;
            weightsRegion.put(entry.key,region);
        }
        System.out.println(weightsRegion);
    }

    public String fetchCalcResult() {
        Random random = new Random();
        //random.nextInt(totalWeight) 生成一个介于 0（包含）到 totalWeight（不包含）之间的随机整数 randomValue。
        int randomValue = random.nextInt(totalWeight);
        Set<Map.Entry<String, String>> set = weightsRegion.entrySet();
        Iterator<Map.Entry<String, String>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            String value =  entry.getValue();
            String[] ragionValue = value.split(",");
            if(Integer.valueOf(ragionValue[0]) < randomValue && Integer.valueOf(ragionValue[1]) > randomValue){
                //System.out.println(entry.getKey());
               return entry.getKey();
            }

        }
        // 初始化一个 cumulativeWeight 变量为 0，用于累计权重
        //数据区间
       /* int cumulativeWeight = 0;
        for (WeightEntry entry : weightEntries) {
            int start = cumulativeWeight;
            cumulativeWeight += entry.weight;
            if (randomValue < cumulativeWeight) {
                return entry.key;
            }
        }*/
        return null;
    }

    private static class WeightEntry {
        String key;
        int weight;

        public WeightEntry(String key, int weight) {
            this.key = key;
            this.weight = weight;
        }
    }
}
